<template>
  <div>
    <div v-if="type==='datetime'" class="van-datetimesec-picker">
      <van-datetime-picker
        v-model="dateValue"
        :type="getTimerType"
        v-bind="datetimePickerProps"
        :formatter="formatter"
        :min-date="minDate"
        :max-date="maxDate"
        @cancel="$emit('cancel')"
        @confirm="handleConfirm"
        @change="changeSecond"
      />
      <van-picker
        :columns="columns"
        v-bind="pickerProps"
        :default-index="secondIdx"
        @change="handleChange"
      />
    </div>
    <div v-else>
      <van-datetime-picker
        v-model="dateValue"
        :type="getTimerType"
        :class="{'year-picker' : type === 'year'}"
        :formatter="formatter"
        :min-date="minDate"
        :max-date="maxDate"
        v-bind="datetimePickerProps"
        @cancel="$emit('cancel')"
        @confirm="handleConfirm"
      />
    </div>
  </div>
</template>

<script>
import { parseTime } from '@/utils'

export default {
  name: 'VanDatetimesecPicker',
  props: {
    // 时间类型 可选值为 year(年) month(年-月) date(年-月-日) datehour(年-月-日-时) datetime(年-月-日-时-分-秒)
    type: {
      type: String,
      default: 'datetime'
    },
    value: {
      type: String,
      default: ''
    },
    titleType: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      secondIdx: 0,
      second: 0,
      datetimePickerProps: { 'visible-item-count': 5, title: '开始时间' },
      pickerProps: { 'visible-item-count': 5 },
      dateValue: null,
      minDate: new Date(1000, 0, 1),
      maxDate: new Date(),
      columns: Array(60).fill().map((_, i) => `0${i}`.slice(-2) + '秒')
    }
  },
  computed: {
    getTimerType() {
      return (this.type === 'year' || this.type === 'month') ? 'year-month' : this.type
    },
    dateFormatter() {
      let formatter = ''
      switch (this.type) {
        case 'date':
          formatter = '{y}-{m}-{d}'
          break
        case 'year':
          formatter = '{y}'
          break
        case 'year-month':
        case 'month':
          formatter = '{y}-{m}'
          break
        case 'datehour':
          formatter = '{y}-{m}-{d} {h}'
          break
        case 'datetime':
          formatter = '{y}-{m}-{d} {h}:{i}:{s}'
          break
      }
      return formatter
    }
  },
  watch: {
    value: {
      handler() {
        this.dateValue = this.value ? new Date(this.value) : new Date()
      },
      immediate: true
    },
    titleType: {
      handler(newVal) {
        if (newVal === 'start') {
          this.datetimePickerProps = { 'visible-item-count': 5, title: '开始时间' }
        } else if (newVal === 'end') {
          this.secondIdx = 0
          this.second = this.minDate.getSeconds()
          this.datetimePickerProps = { 'visible-item-count': 5, title: '结束时间' }
          this.columns = Array(60 - this.second).fill().map((_, i) => `0${i + this.second}`.slice(-2) + '秒')
        } else {
          this.datetimePickerProps = { 'visible-item-count': 5, title: '选择时间' }
        }
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      if (this.type === 'datetime') {
        if (!this.value) {
          this.secondIdx = new Date().getSeconds()
          this.second = new Date().getSeconds()
          this.columns = Array(this.secondIdx).fill().map((_, i) => `0${i}`.slice(-2) + '秒')
        } else {
          this.secondIdx = new Date(this.value).getSeconds()
          this.second = new Date(this.value).getSeconds()
          this.columns = Array(60).fill().map((_, i) => `0${i}`.slice(-2) + '秒')
        }
      }
    })
  },
  methods: {
    formatter(type, val) {
      if (type === 'year') {
        return val + '年'
      }
      if (type === 'month') {
        return val + '月'
      }
      if (type === 'day') {
        return val + '日'
      }
      if (type === 'hour') {
        return val + '时'
      }
      if (type === 'minute') {
        return val + '分'
      }
      return val
    },
    handleConfirm(val) {
      if (this.type === 'datetime') {
        val.setSeconds(this.second)
      }
      if (this.titleType === 'start') {
        this.minDate = new Date(val.getTime())
        this.secondIdx = 0
      }
      this.$emit('input', parseTime(new Date(val.getTime()), this.dateFormatter))
    },
    handleChange() {
      if (this.type === 'datetime') {
        this.second = Number(arguments[1].replace('秒', ''))
        this.secondIdx = arguments[2]
      }
    },
    changeSecond(type) {
      if (this.type === 'datetime') {
        const val = type.getValues()
        const time = {
          y: val[0].replace('年', '-'),
          m: val[1].replace('月', '-'),
          d: val[2].replace('日', ''),
          h: val[3].replace('时', ':'),
          i: val[4].replace('分', '')
        }
        const time1 = time.y + time.m + time.d + ' ' + time.h + time.i
        if (this.titleType === 'end') {
          if (time1 === parseTime(this.minDate, '{y}-{m}-{d} {h}:{i}')) {
            this.secondIdx = this.minDate.getSeconds()
            this.columns = Array(60 - this.secondIdx).fill().map((_, i) => `0${i + this.secondIdx}`.slice(-2) + '秒')
            this.second = 0
          } else {
            this.columns = Array(60).fill().map((_, i) => `0${i}`.slice(-2) + '秒')
            this.second = this.secondIdx
          }
        } else {
          if (time1 === parseTime(this.maxDate, '{y}-{m}-{d} {h}:{i}')) {
            this.columns = Array(this.secondIdx).fill().map((_, i) => `0${i}`.slice(-2) + '秒')
            this.second = this.secondIdx
          } else {
            this.columns = Array(60).fill().map((_, i) => `0${i}`.slice(-2) + '秒')
            this.second = this.secondIdx
          }
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.van-datetimesec-picker {
  display: flex;
  .van-picker:first-of-type {
    flex: 5;
    ::v-deep {
      .van-picker__toolbar {
        width: 120%;
      }
      .van-picker__frame {
        width: 100%;
      }
    }
  }
  .van-picker:last-of-type {
    flex: 1;
    margin-top: 44px;
  }
}
::v-deep.year-picker {
  .van-picker__columns {
    .van-picker-column{
      &:nth-child(2) {
        display: none;
      }
    }
  }
}
</style>
